package com.qdlc.p2p.biz.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.qdlc.p2p.biz.service.ScoreService;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.dal.common.model.jpa.OrderFilter.OrderType;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.common.model.jpa.QueryParam;
import com.qdlc.p2p.dal.common.model.jpa.SearchFilter.Operators;
import com.qdlc.p2p.dal.dao.ScoreDao;
import com.qdlc.p2p.dal.dto.Score;
import com.qdlc.p2p.dal.model.ScoreModel;

@Service("scoreService")
public class ScoreServiceImpl implements ScoreService {

    @Resource
    private ScoreDao scoreDao;

    public PageDataList<ScoreModel> findPageList(ScoreModel model) {
        QueryParam param = QueryParam.getInstance();
        if (StringUtil.isNotBlank(model.getSearchName())) {
            param.addParam("user.userName", Operators.LIKE, model.getSearchName().trim());
        } else {
            if (StringUtil.isNotBlank(model.getUserName())) {
                param.addParam("user.userName", Operators.LIKE, model.getUserName().trim());
            }
            if (StringUtil.isNotBlank(model.getStartTime())) {
                Date start = DateUtil.valueOf(model.getStartTime() + " 00:00:00");
                param.addParam("addTime", Operators.GTE, start);
            }
            if (StringUtil.isNotBlank(model.getEndTime())) {
                Date end = DateUtil.valueOf(model.getEndTime() + " 23:59:59");
                param.addParam("addTime", Operators.LTE, end);
            }
        }

        param.addOrder(OrderType.DESC, "id");
        param.addPage(model.getPage(), model.getRows());
        PageDataList<Score> itemPage = scoreDao.findPageList(param);
        List<ScoreModel> modelList = new ArrayList<ScoreModel>();
        PageDataList<ScoreModel> modelPage = new PageDataList<ScoreModel>();
        if (itemPage != null && itemPage.getList() != null && itemPage.getList().size() > 0) {
            for (int i = 0; i < itemPage.getList().size(); i++) {
                Score item = itemPage.getList().get(i);
                ScoreModel model_ = ScoreModel.instance(item);
                if (item.getUser() != null) {
                    model_.setUserName(item.getUser().getUserName());
                }
                modelList.add(model_);
            }
        }
        modelPage.setPage(itemPage.getPage());
        modelPage.setList(modelList);
        return modelPage;
    }

    public Score findByUserId(long userId) {
        return scoreDao.findObjByProperty("user.userId", userId);
    }
}
